from django.shortcuts import render
from django.http import JsonResponse
import json
from openai import AzureOpenAI

# Azure OpenAI 配置参数
AZURE_ENDPOINT = "https://test-xianzhigao.openai.azure.com/"
AZURE_API_KEY = "67266a3fc43443aa8cbe30863f8c5e13"
AZURE_API_VERSION = "2024-02-01"

# 初始化全局 Azure OpenAI 客户端
azure_client = AzureOpenAI(
    azure_endpoint=AZURE_ENDPOINT,
    api_key=AZURE_API_KEY,
    api_version=AZURE_API_VERSION,
)

def index(request):
    """
    首页路由方法
    """
    try:
        print("进入首页")
        return render(request, 'django_gpt_01/index.html')
    except Exception as e:
        print(f"Error rendering index page: {str(e)}")
        return render(request, 'error.html', {'error': str(e)})


def chat_with_gpt(request):
    if request.method == 'POST':
        try:
            # 解析请求数据
            data = json.loads(request.body)
            input_text = data.get('message', '')
            chat_history = data.get('history', [])

            # print(f"Input text: {input_text}")

            # 使用全局客户端
            response = azure_client.chat.completions.create(
                model="gpt-4o-2024-08-06-GlobalStandard",
                messages=[
                    {"role": "system", "content": "You are a helpful assistant."},
                    *chat_history,
                    {"role": "user", "content": input_text}
                ]
            )

            # 获取回复内容
            reply = response.choices[0].message.content
            # print(f"Azure GPT response: {reply}")

            # 更新对话历史
            chat_history.append({'role': 'user', 'content': input_text})
            chat_history.append({'role': 'assistant', 'content': reply})

            return JsonResponse({
                'history': chat_history,
                'reply': reply
            }, json_dumps_params={'ensure_ascii': False})

        except Exception as e:
            print(f"Error: {e}")
            return JsonResponse({'error': str(e)}, status=500)

    return JsonResponse({'error': 'Only POST method allowed'}, status=405)